package com.hmall.order.interceptor;

import com.hmall.order.utils.UserHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {

    //获取请求头
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //获取请求头
        String header = request.getHeader("authorization");
        //判断用户是否存在
        if(StringUtils.isEmpty(header)){
            //用户未登录
            response.setStatus(403);
            return false;
        }
        //转换用户id
        Long userId = Long.valueOf(header);
        //存入当前线程中
        UserHolder.setUser(userId);
        //放行
        return true;
    }

    //结束清理业务
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
